package com.example.pagingdemo.paging.movie;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.paging.PagedListAdapter;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.example.pagingdemo.databinding.ItemMovieBinding;
import com.example.pagingdemo.model.Movie;

/**
 * @author: tuyrt7 on 2020/9/9.
 */
public class MoviePageListAdapter extends PagedListAdapter<Movie, MoviePageListAdapter.ViewHolder> {

    private Context mContext;

    public MoviePageListAdapter(Context context) {
        super(DIFF_CALLBACK);
        mContext = context;
    }

    private static DiffUtil.ItemCallback<Movie> DIFF_CALLBACK = new DiffUtil.ItemCallback<Movie>() {
        @Override
        public boolean areItemsTheSame(@NonNull Movie oldItem, @NonNull Movie newItem) {
            return oldItem.id == newItem.id;
        }

        @Override
        public boolean areContentsTheSame(@NonNull Movie oldItem, @NonNull Movie newItem) {
            return oldItem.equals(newItem);
        }
    };


    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemMovieBinding binding = ItemMovieBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Movie movie = getItem(position);
        holder.bindata(movie);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private ItemMovieBinding mBinding;

        public ViewHolder(@NonNull ItemMovieBinding binding) {
            super(binding.getRoot());
            mBinding = binding;
        }

        public void bindata(Movie movie) {
            mBinding.setMovie(movie);
        }
    }
}
